﻿using Abp.Domain.Entities.Auditing;
using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SFGX.Mango.BoxUses
{
	public class BoxUseManager : IBoxUseManager
	{
		private readonly IRepository<BoxUse> _boxUseRepository;

		public BoxUseManager(IRepository<BoxUse>  boxUseRepository) {
			_boxUseRepository = boxUseRepository;
		}

		public async Task BoxHandlerAsync(int id,string openId, int boxUsed)
		{
			var entity = _boxUseRepository.Get(id);

			if (entity.ExpressPerson.OpenId != openId  )
				throw new UserFriendlyException("只能本人处理!");

			if (entity.BoxReceiveCount< boxUsed)
				  throw new UserFriendlyException("使用的数量比领取的多!");


			entity.BoxUseCount = boxUsed;
			entity.IsHandler = true;//

			await _boxUseRepository.UpdateAsync(entity);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="boxUse"></param>
		/// <returns></returns>
		public async Task BuyBoxAsync(BoxUse boxUse)
		{
			await _boxUseRepository.InsertAsync(boxUse);
		}

		 
		public async Task<IReadOnlyList<BoxUse>> GetListAsync(string openId)
		{
			var list = await _boxUseRepository
				.GetAll()
				.Include(e => e.ExpressPerson)
				 
				.OrderByDescending(e => e.CreationTime)
				.Take(64)
				.ToListAsync();

			return list;
		}
	}
}
